package com.mogu.comment.service.impl;

import com.mogu.comment.pojo.Email;
import com.mogu.comment.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * Description:不在能知，而在能行
 *
 * @author: 梁西华
 * @date: 2020/6/15/11:23
 **/
@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String sendFrom;

    @Autowired
    JavaMailSender javaMailSender;

    /**
     * 异步处理，发送邮件
     * @param email
     * @return
     */
    @Async
    @Override
    public String sendEmail(Email email) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(sendFrom);
            simpleMailMessage.setTo(email.getSendTo());
            simpleMailMessage.setText(email.getMessage());
            simpleMailMessage.setSubject(email.getSubject());

            javaMailSender.send(simpleMailMessage);
            return "success";
        } catch (MailException e) {
            //e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "fail";
    }
}
